package com.teaching.teachingsupport.common.advice;

import com.teaching.teachingsupport.common.api.Result;
import com.teaching.teachingsupport.common.enums.ResultStatusEnum;
import com.teaching.teachingsupport.common.exception.BaseException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(BaseException.class)
    public Result<Object> handleBaseException(BaseException e) {
        log.error("业务异常：{}", e.getMessage(), e);
        return Result.failed(ResultStatusEnum.FAIL, e.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<Object> handleValidException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        String message = null;
        if (bindingResult.hasErrors()) {
            FieldError fieldError = bindingResult.getFieldError();
            if (fieldError != null) {
                message = fieldError.getDefaultMessage();
            }
        }
        log.error("参数校验异常：{}", message, e);
        return Result.failed(ResultStatusEnum.VALIDATE_FAILED, message == null ? "参数校验失败" : message);
    }

    @ExceptionHandler(BindException.class)
    public Result<Object> handleBindException(BindException e) {
        BindingResult bindingResult = e.getBindingResult();
        String message = null;
        if (bindingResult.hasErrors()) {
            FieldError fieldError = bindingResult.getFieldError();
            if (fieldError != null) {
                message = fieldError.getDefaultMessage();
            }
        }
        log.error("参数绑定异常：{}", message, e);
        return Result.failed(ResultStatusEnum.VALIDATE_FAILED, message == null ? "参数绑定失败" : message);
    }

    @ExceptionHandler(Throwable.class)
    public Result<Object> handleException(Throwable e) {
        log.error("系统异常：{}", e.getMessage(), e);
        return Result.failed(ResultStatusEnum.INTERNAL_SERVER_ERROR, "系统异常，请联系管理员");
    }
} 